package com.ea.common.oauth2Exception;

import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSONObject;
import com.ea.common.result.ErrorCode;
import com.ea.common.result.Result;
import lombok.AllArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

@Component
@AllArgsConstructor
public class CustomAuthExceptionEntryPoint implements AuthenticationEntryPoint {

  @Override
  public void commence(HttpServletRequest httpServletRequest,
                       HttpServletResponse response, AuthenticationException e)
          throws IOException {
    response.setCharacterEncoding(StandardCharsets.UTF_8.name());
    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
    Result<String> result = Result.fail(
            ErrorCode.USER_LOGIN_ERROR_LOGIN_EXPIRE.getCode(),
            ErrorCode.USER_LOGIN_ERROR_LOGIN_EXPIRE.getMsg());
    result.setCode(HttpStatus.HTTP_UNAUTHORIZED);
    if (e != null) {
      result.setData(e.getMessage());
      if (e.getMessage().contains("Full authentication is required to access this resource")) {
        result.setMsg("如要使用此服务，请先登录");
      }
    }
    response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
    PrintWriter printWriter = response.getWriter();
    printWriter.append(JSONObject.toJSONString(result));
  }
}
